package com.id.supaclean.widget

import android.animation.ArgbEvaluator
import android.animation.ObjectAnimator
import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import android.widget.FrameLayout
import com.id.supaclean.R

class HeaderView(context: Context, attrs: AttributeSet?) : FrameLayout(context, attrs) {

    private val scanProgressView by lazy { findViewById<ScanProgressView>(R.id.scanProgress) }

    private val startColor = Color.parseColor("#2E425F")
    private val endColor = Color.parseColor("#D60000")

    init {
        inflate(context, R.layout.item_focus_on_header, this)
        setBackgroundColor(startColor)
    }

    fun startScan(duration: Long, complete: (() -> Unit)? = null) {
        val animator = ObjectAnimator.ofObject(
            this, "backgroundColor", ArgbEvaluator(), startColor, endColor
        ).apply {
            this.duration = duration
            var isCall = false
            addUpdateListener {
                scanProgressView.setProgress(it.animatedFraction)
                if (it.animatedFraction == 1f && !isCall) {
                    isCall = true
                    complete?.invoke()
                }
            }
        }
        animator.start()
    }

}